#!/usr/bin/env node
const express = require('express');
const cors = require("cors");
const path = require('path')
const app = express();
app.use(cors())

const multer = require('multer');

let storage = multer.diskStorage({
  //设置存储路径
  destination: (req, file, cb) => {
    cb(null, path.resolve(__dirname + "/uploads"));
  },
  //设置存储的文件名
  filename: (req, file, cb) => {
    //获取文件的扩展名
    let extname = path.extname(file.originalname);
    const filename = file.fieldname + "-" + Date.now() + extname;
    cb(null, filename);
  }
})

const upload = multer({ storage });

const pythonFilePath = path.join(__dirname, '../model/node.py')

app.post('/img', upload.single('image'), (req, res) => {
  const fullPath = req.file.path

  console.log(pythonFilePath, fullPath)
  const spawn = require('child_process').spawn
  const py = spawn('python', [pythonFilePath, fullPath])

  let message = ''
  py.stdout.on('data', function (res) {
    const msg = res.toString()
    message += msg
  })

  py.stdout.on('close', () => {
    let result = message.match(/"(.*)"/)?.[1]
    console.log(result)
    result = result && result.replace(/\\u(\w{4})/g, (match, p1) => String.fromCharCode(parseInt(p1, 16)));
    res.send(JSON.stringify({ result }))
  })
});

// 启动服务器
app.listen(8888, () => {
  console.log('已启动8888端口~');
})